package com.finalministry.server;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.collections.ListUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.finalministry.database.dao.DaoFactory;

import com.finalministry.server.beans.SqlQueryRequest;

/**
 * This service provides functionality during the developing stage
 * 
 * @author lussopi
 */
@Path("/developer")
public class ServiceDeveloper {

	@POST
	@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	@Path("/executeSQL")
	public Response executeSQL(SqlQueryRequest request, @HeaderParam("Access-Control-Request-Headers") String requestH) {

		System.out.println("[" + request.getNote() + "]\n" + request.getSql() + "\n--------------\n");

		@SuppressWarnings("unchecked")
		List<Object> result = ListUtils.EMPTY_LIST;

		try {
			result = DaoFactory.getInstance().getDeveloperDAO().executeSQL(request.getSql());
		} catch (Exception e) {
			return Response.status(202).entity(e.getMessage()).build();
		}

		JSONObject responseJSON = new JSONObject();
		JSONArray jsonROWs = new JSONArray();

		for (Object object : result) {

			JSONArray jsonCOLUMNs = new JSONArray();

			if (object instanceof Object[]) {

				Object[] objArray = (Object[]) object;
				//
				// for (Object obj : objArray) {
				// jsonCOLUMNs.put(obj);
				// }

				for (Object obj : objArray) {
					jsonROWs.put(obj);
				}

				// jsonROWs.put(objArray);
			} else {

				jsonROWs.put(object);
			}
		}
		try {
			responseJSON.put("result", jsonROWs);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return Response.ok().entity(responseJSON.toString()).build();
	}
}
